import { defineConfig, loadEnv, ConfigEnv, UserConfig } from 'vite';
import { resolve } from 'path';
import pkg from './package.json';
import { format } from 'date-fns';
import { createVitePlugin, createViteProxy, wrapperEnv } from './vite.helper';

const { dependencies, devDependencies, name, version } = pkg;
const __APP_INFO__ = {
  pkg: { dependencies, devDependencies, name, version },
  lastBuildTime: format(new Date(), 'yyyy-MM-dd HH:mm:ss'),
};

/**
 * @description: 处理文件路径
 * @param dir
 */
export const pathResolve = (dir: string) => {
  return resolve(process.cwd(), '.', dir);
};

// https://vitejs.dev/config/
export default defineConfig(({ command, mode }: ConfigEnv): UserConfig => {
  const root = process.cwd();
  const env = loadEnv(mode, root);
  console.log('root', root);
  console.log('mode', mode);
  console.log('command', command);
  const viteEnv = wrapperEnv(env as unknown as ViteEnv);
  const { VITE_APP_TITLE, VITE_APP_PUBLIC_PATH, VITE_APP_DROP_CONSOLE, VITE_APP_PORT, VITE_APP_PROXY } = viteEnv;
  console.log('viteEnv', viteEnv);
  const isBuild = command === 'build';
  // 输出文件夹
  const OUTPUT_DIR = 'Netease-Cloud-music';
  const ASSETS_DIR = 'static';

  return {
    base: VITE_APP_PUBLIC_PATH,
    plugins: createVitePlugin(viteEnv as ViteEnv, isBuild),
    // 定义全局常量替换方式。
    define: {
      __APP_INFO__: JSON.stringify(__APP_INFO__),
    },
    resolve: {
      alias: [
        {
          find: '@',
          replacement: pathResolve('src') + '/',
        },
      ],
      // 忽略后缀名的配置选项, 添加 .vue 选项时要记得原本默认忽略的选项也要手动写入
      extensions: ['.vue', '.ts', '.js', '.jsx', '.tsx', '.mjs', '.json'],
    },
    server: {
      host: true,
      https: false,
      port: VITE_APP_PORT,
      proxy: createViteProxy(VITE_APP_PROXY),
    },
    // 打包
    build: {
      target: 'es2015',
      outDir: OUTPUT_DIR,
      assetsDir: ASSETS_DIR,
      terserOptions: {
        compress: {
          keep_infinity: true,
          drop_console: VITE_APP_DROP_CONSOLE,
        },
      },
      minify: 'terser',
      chunkSizeWarningLimit: 2000,
    },
  };
});
